﻿using AdinZ.Common;
using Aliyun.OpenServices;
using Aliyun.OpenServices.OpenStorageService;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;


/**
* @Author: AdinZ
* @Q  Q : 1454269
* @Email:adinz@adinz.com
* @Created: 2014/5/1 17:40:20
*
* */
namespace Novel.Collection
{
    public class Collection 
    {
        static Sys.BLL.novel_article bll_art = new Sys.BLL.novel_article();
        static Sys.BLL.novel_chapter bll_chap = new Sys.BLL.novel_chapter();
        static ClientConfiguration clientConfig = new ClientConfiguration();
        static ObjectMetadata metadata = new ObjectMetadata();
        private static string novelName, novelAuthor;
        static string StrPath;

        public static void Start(int sId, int eId, bool IsLocal)
        {
            StrPath = System.Web.HttpContext.Current.Server.MapPath("/");
            int chapterId = 0;
            for (int ID = sId; ID < eId + 1; ID++)
            {

                WriteLog("开始采集【" + ID + "】.......\n");
                Sys.Model.novel_article book = new Sys.Model.novel_article();
                book = RegexData.CooleArt(NetServer.Get("http://www.qingdi.com/book/" + ID + ".html"));
                int Aid = 0; 
                if (book != null) { 
                    WriteLog( "\n\n采集到小说【" + book.Title + "】，作者【" + book.Author + "】\n"); 
                }
                if (bll_art.Exists(book.Title, book.Author)) { /*已存在小说,获取小说id*/ 
                    Aid = bll_art.GetID(book.Title, book.Author);
                    WriteLog( "小说【" + book.Title + "】，作者【" + book.Author + "】已存在\n");
                    chapterId = bll_chap.GetChapterNum(Aid);
                }
                else
                {
                    Aid = bll_art.Add(book);
                    book.ID = Aid;
                    if (!bll_art.ExistsCover(Aid))
                    {
                        object obj = (object)book;
                        Thread t = new Thread(UploadCover);
                        t.IsBackground = true;
                        t.Start(obj);
                    }
                    WriteLog( "小说【" + book.Title + "】，作者【" + book.Author + "】成功添加到数据库中\n");
                }//添加小说








                if (Aid > 0)
                {
                    Dictionary<string, string> list = new Dictionary<string, string>();
                    list = RegexData.CooleChapter(NetServer.Get(book.InfoUrl));
                    string url = book.InfoUrl.Replace("index.html", "");
                    url = url.Replace("/html/", "/txt/"); 
                    int chapterID = 0;
                    if (list != null) { WriteLog( "当前采集ID【" + ID + "】小说【" + book.Title + "】，作者【" + book.Author + "】采集了【" + list.Count + "】章\n"); }
                    foreach (KeyValuePair<string, string> item in list)
                    {
                        if (chapterID >= chapterId)
                        {
                            Sys.Model.novel_chapter model_chap = new Sys.Model.novel_chapter();
                            model_chap.Aid = Aid;
                            model_chap.Chaptername = item.Value;//本章标题
                            model_chap.Chapternum = chapterID+1;//章ID
                            model_chap.Created = DateTime.Now;
                            model_chap.Isvip = 0;
                            model_chap.Modified = DateTime.Now;
                            model_chap.Price = 0;
                            model_chap.Size = 0;
                            model_chap.Status = 1;
                            model_chap.Articlepath = url + item.Key + ".txt";
                            model_chap.CollectionMark = item.Key.Trim();
                            if (!bll_chap.Exists(Aid, model_chap.Chaptername, item.Key.Trim()))
                            {
                                int chaptrNum;
                                novelName = book.Title;
                                novelAuthor = book.Author;
                                chaptrNum = bll_chap.Add(model_chap);
                                if (IsLocal)
                                {

                                    model_chap.ID = chaptrNum;
                                    object obj = (object)model_chap;
                                    Thread t = new Thread(UploadChapter);
                                    t.IsBackground = true;
                                    t.Start(obj);
                                }

                                //WriteLog( "当前采集ID【" + ID + "】小说【" + book.Title + "】，作者【" + book.Author + "】【" + item.Value + "】成功添加到数据库\n");
                            }
                        }
                        chapterID++;
                       // else { WriteLog("当前采集ID【" + ID + "】小说【" + book.Title + "】，作者【" + book.Author + "】【" + item.Value + "】已存在\n"); }
                    }
                    WriteLog( "当前采集ID【" + ID + "】小说【" + book.Title + "】，作者【" + book.Author + "】所有章节成功添加到数据库\n");

                }
















            }
        }

        private static void UploadCover(object obj)
        {
            Sys.Model.novel_article model = (Sys.Model.novel_article)obj;
            AdinZ.Common.DownloadFile downloadCover = new AdinZ.Common.DownloadFile();
            string temPath = "cover/cover_" + model.ID + ".jpg";
            downloadCover.StrFileName = StrPath + temPath;
            downloadCover.StrUrl = model.Cover;
            if (downloadCover.Download())
            {

                try
                {
                    using (var fs = File.Open(downloadCover.StrFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite))
                    {
                        metadata.ContentType = "image/jpeg";
                        if (AdinZ.Common.OssUpload.Upload(temPath, fs, metadata, clientConfig))
                        {
                            bll_art.UpdateCover(model.ID, downloadCover.StrFileName, 1);
                        }
                    }
                    File.Delete(downloadCover.StrFileName);
                }
                catch (Exception e)
                {
                }

            }
        }

        public static void WriteLog(string log)
        {
            Common.Write(StrPath + "collection.log", log);
        }


        private static void UploadChapter(object obj)
        {
            Sys.Model.novel_chapter model = (Sys.Model.novel_chapter)obj;
            AdinZ.Common.DownloadFile download = new AdinZ.Common.DownloadFile();
            string temPath = "chapter/" + model.ID + ".txt";
            download.StrFileName = StrPath + temPath;
            download.StrUrl = model.Articlepath;
            if (download.Download())
            {
                string str = File.ReadAllText(download.StrFileName, Encoding.Default); //获得整个文本
                str = "\t" + model.Chaptername + "\r\n\r\n" + str;
                try
                {
                    using (var fs = File.Open(download.StrFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite))
                    {
                        metadata.ContentType = "text/plain";
                        if (AdinZ.Common.OssUpload.Upload(download.StrFileName, fs, metadata, clientConfig))
                        {
                            bll_chap.UpdateChapterPath(model.ID, download.StrFileName, 1, download.lDownloadFile);
                        }
                    }
                    File.Delete(download.StrFileName);
                }
                catch (Exception e)
                {
                }
            }
        }



    }
}
